import {
  useEffect,
  useMemo,
  useState,
  ForwardedRef,
  useImperativeHandle,
  MutableRefObject,
  useCallback,
  useRef,
} from 'react';
import type { ISearchResultData } from '../../../SearchEngine/store/hooks/useJumpResult';
import { IConfigItemEngineProps } from '../web';
export type ISearchEngineData = Omit<ISearchResultData, 'IndexName'>;
export type IConfigs = {
  configs: IConfigItemEngineProps['indexIibraryConfig'];
  engineProps: IConfigItemEngineProps;
};
export type ISearchResultContentRef = {
  getSelected: () => object[];
  getData: () => object[];
  refresh: () => void;
  clearSelected: () => void;
  getSearchParams: () => object,
  setSearchParams: (params: object) => void,
  setsearchKeyword: (val: string) => void,
  clearRightPanel: () => void,
  setshowTeam: (val: boolean) => void,
  setshowPerson: (val: boolean) => void,
  setShowImgSearch: (val: boolean) => void,

};

export type ISearchResultMainRef = {
  getSelectedAll: () => object;
  getDataAll: () => object;
  load: (data: ISearchResultData) => void;
} & ISearchResultContentRef;

export default function useConfigs(
  { configs, engineProps }: IConfigs,
  ref: ForwardedRef<ISearchResultMainRef>,
) {
  const showConfigs = useMemo(() => {
    return configs.filter((item) => item.isShow !== false && item.configs?.length);
  }, [configs]);
  const searchEngineDataRef = useRef<ISearchResultData | undefined>(undefined);
  // 获取第一次的搜索数据
  const firstSearchEngineData = useMemo(() => {
    //@ts-ignore
    const pageId = 'page/' + engineProps.inbiz.pageId;
    //@ts-ignore

    let storage = localStorage.getItem('_searchEngineStatus');
    if (storage) {
      sessionStorage.setItem('_searchEngineStatus', storage);
      localStorage.removeItem('_searchEngineStatus');
    } else {
      storage = sessionStorage.getItem('_searchEngineStatus');
    }
    const searchEngineData = JSON.parse(storage || '{}') as ISearchResultData;

    // 用于搜索入口跳转页面后，通过该事件能获取到搜索数据
    engineProps.emit?.('onSearchData', searchEngineData);
    return searchEngineData;
  }, []);
  // 搜索入口数据
  const [searchEngineData, $searchEngineData] = useState(() => {
    const searchData = {};
    showConfigs.forEach((item) => {
      searchData[item.IndexName] = {};
    });
    searchEngineDataRef.current = firstSearchEngineData;
    return updateSearchData(searchData, firstSearchEngineData) as {
      [key in string]: ISearchEngineData;
    };
  });

  const [activeIndexName, $activeIndexName] = useState(() => {
    return firstSearchEngineData?.IndexName;
  });
  // useUpdateEffect(() => {
  //   $searchEngineData(() => {
  //     const searchData = {};
  //     showConfigs.forEach((item) => {
  //       searchData[item.IndexName] = {};
  //     });
  //     return searchData;
  //   });
  // }, [showConfigs]);

  const [activeKey, $activeKey] = useState(() => {
    if (firstSearchEngineData.IndexName?.length) {
      return firstSearchEngineData.IndexName[0] === '_all_'
        ? showConfigs[0]?.IndexName
        : firstSearchEngineData.IndexName[0];
    } else {
      return showConfigs[0]?.IndexName;
    }
  });

  // 监听事件, 用于关联组件
  const searchEngineDataChange = useCallback(
    (_searchId: string, resultId: string, data: ISearchResultData) => {

      if (engineProps.controlId === resultId && data.IndexName?.length) {
        engineProps.inbiz(engineProps.controlId)?.clearRightPanel?.()
        if (data.IndexName[0] !== '_all_') {
          $activeKey(data.IndexName[0]);
        }
        searchEngineDataRef.current = data;
        $searchEngineData(updateSearchData({ ...searchEngineData }, data));
        $activeIndexName(data.IndexName);
        //@ts-ignore
        // sessionStorage.setItem(
        //   'page/' + engineProps.inbiz.pageId + '_searchEngine',
        //   JSON.stringify(data),
        // );
      }
    },
    [searchEngineData],
  );
  useEffect(() => {
    if (engineProps.inbiz.browser.designer) {
      return;
    }
    // 搜索组件在页面内
    engineProps.inbiz.on('search._result', searchEngineDataChange);
    // 搜索组件在全局布局中
    engineProps.inbiz.global.on('search._result', searchEngineDataChange);

    return () => {
      if (engineProps.inbiz.browser.designer) {
        return;
      }
      engineProps.inbiz.off('search._result');
      engineProps.inbiz.global.off('search._result');
    };
  }, [configs, searchEngineData]);

  const refs = useMemo(() => {
    return showConfigs.reduce((pre, next) => {
      pre[next.IndexName] = { current: null };
      return pre;
    }, {}) as { [key: string]: MutableRefObject<ISearchResultContentRef> };
  }, [showConfigs]);

  // 对外暴露接口
  useImperativeHandle(
    ref,
    () => ({
      getSearchEngineData: () => {
        // 获取来自搜索入口的数据
        return searchEngineDataRef.current;
      },
      getSelected: () => {
        return refs[activeKey!]?.current?.getSelected();
      },
      getData: () => {
        return refs[activeKey!]?.current?.getData();
      },
      getSelectedAll: () => {
        return Object.entries(refs).reduce((pre, [key, item]) => {
          pre[key] = item?.current?.getSelected();
          return pre;
        }, {});
      },
      getDataAll: () => {
        return Object.entries(refs).reduce((pre, [key, item]) => {
          pre[key] = item?.current?.getData();
          return pre;
        }, {});
      },
      load: (params: ISearchResultData) => {
        searchEngineDataChange('', engineProps.controlId, params);
      },
      getActiveTab: () => activeKey,
      refresh: () => refs[activeKey!]?.current?.refresh?.(),
      clearSelected: () => refs[activeKey!]?.current?.clearSelected?.(),
      getSearchParams: () => refs[activeKey!]?.current?.getSearchParams?.(),
      setSearchParams: (obj) => refs[activeKey!]?.current?.setSearchParams?.(obj),
      setsearchKeyword: (val) => refs[activeKey!]?.current?.setsearchKeyword?.(val),
      clearRightPanel: () => refs[activeKey!]?.current?.clearRightPanel?.(),
      setShowImgSearch: (val) => refs[activeKey!]?.current?.setShowImgSearch(val),
      setshowTeam: (val) => refs[activeKey!]?.current?.setshowTeam(val),
      setshowPerson: (val) => refs[activeKey!]?.current?.setshowPerson(val),
    }),
    [refs, activeKey, searchEngineData],
  );
  const showTabs = useMemo(() => {
    const displayRule = engineProps.displayRule || '2';
    if (activeIndexName?.length && activeIndexName[0] != '_all_' && displayRule == '2') {
      //@ts-ignore
      return showConfigs.filter((item) => activeIndexName.includes(item.IndexName));
    } else {
      return showConfigs;
    }
  }, [showConfigs, activeIndexName, engineProps.displayRule]);
  useEffect(() => {
    if (
      engineProps.inbiz.browser.designer &&
      !showTabs.find((item) => item.IndexName === activeKey)
    ) {
      $activeKey(showTabs[0]?.IndexName);
    }
  }, [showTabs]);
  return { showConfigs: showTabs, searchEngineData, activeKey, $activeKey, refs };
}

const updateSearchData = (searchData: object, searchEngineData?: ISearchResultData) => {
  if (searchEngineData?.IndexName?.length) {
    if (searchEngineData.IndexName[0] == '_all_') {
      Object.entries(searchData).forEach(([key]) => {
        searchData[key] = {
          ...searchEngineData,
        };
        delete searchData[key].IndexName;
      });
    } else {
      const { IndexName, ...other } = searchEngineData;
      const searchDataKeys = Object.keys(searchData)
      searchDataKeys.forEach(ele => {
        const findKey = IndexName.includes(ele)
        if (findKey) {
          searchData[ele] = { ...other };
        } else {
          searchData[ele] = {
            ...searchData[ele],
            KeyWord: other.KeyWord,
            KeyWords: other.KeyWords,
            IsSynonymSearch: other.IsSynonymSearch
          };
        }

      })
      // IndexName.forEach((item) => {
      //   searchData[item] = { ...other };

      // });
    }
  }
  return searchData as {
    [x: string]: ISearchEngineData;
  };
};
export type IConfigItem = {
  config: Exclude<
    Exclude<IConfigItemEngineProps['indexIibraryConfig'], undefined>[number]['configs'],
    undefined
  >[number] & {
    Mark?: string;
  };
};

export const getDefaultParams = (
  config: IConfigItem['config'],
  value: { PageIndex?: number; pageNumber?: number; groupNum?: string, platform?: 'wap' | 'web' } & ISearchEngineData,
) => {
  const defaultSort = config.sortField?.find((item) => item.enable);
  let Order = defaultSort?.sort;
  let Sort = defaultSort?.IndexFieldName ?? ''
  // Order.sort.sort是因为以前要求绑定多语言
  if (typeof Order === 'object') {
    //@ts-ignore
    if (typeof Order.sort === 'object') {
      Order = Order.sort.sort || 'desc';
    } else {
      Order = Order.sort || 'desc';
    }
  }
   // 因为刷新的时候要把sort条件带上
   const sessionSort = sessionStorage.getItem(`${config.IndexName}_searchSortData`)
   let newsessionSort = {
     order: 'desc',
     IndexFieldName: '',
   }
   if (sessionSort) {
     newsessionSort = JSON.parse(sessionSort)
     Order = newsessionSort.order
     Sort = newsessionSort.IndexFieldName
   }
 

  let PermType = value.PermType || 0
  let index = -1
  if (config.showContents) {
    index = config.showContents.findIndex(element => element == 'authorityFilter')
  }
  
  // 不显示权限时, 默认搜索有权限的
  if (index == -1) {
    PermType = 2
  }

  return {
    PageIndex: value.PageIndex ?? 1,
    PageSize: value.pageNumber || 10,
    IndexName: value.documentType || config.IndexName,
    KeyWord: value.KeyWord || config.defaultSearchCriteria,
    SearchWhere:
      (config.resultsSearchCriteria || '') +
      (config.resultsSearchCriteria && value.SearchWhere ? ' AND ' : '') +
      (value.SearchWhere || ''),
    SearchFields: [...(config.searchField || []), ...(value.SearchFields || [])]
      ?.map((item) => item.IndexFieldName)
      .join(','),
    ExcludesFields: config.excludeField?.map((item) => item.IndexFieldName).join(','),
    HighlightField: config.highlightField?.map((item) => item.IndexFieldName).join(','),
    Sort,
    Order: Order as "desc" | "asc" | undefined,
    groupNum: value.groupNum,
    ModuleName: value.ModuleName,
    PreTags: "<span style='color:var(--search-color)'>",
    PostTags: '</span>',
    IsFuzzySearch: value?.isFuzzySearch ?? true,
    FuzzyFields: [...(value.FuzzyFields || []), ...(config.vagueSearchField || [])]
      ?.map((item) => item.IndexFieldName)
      .join(','),
    Mark: value.ImgMarkId,
    SecondaryWord: value.KeyWords?.slice(1).join(','),
    IsSynonymSearch: value.IsSynonymSearch,
    Platform: value?.platform || 'web',
    PermType,
    searchText: value.searchText,
    fileSearchType: 'all',
    categorySearchWhere: ''
  };
};
